<?php

/**
 * Student
 * @property	int		$id
 * @property    string  $studentNo
 * @property	string	$name
 * @property    string  $sex
 * @property    string  $classId
 * @property    string  $address
 * @property    string  $phone
 * @property	string	$created
 * @property	string	$updated
 */
class Student extends Node
{
    public static function option() {
        return array(
            'table' => 'Student',
            'key' => 'id',
            'columns' => array(
                'id' => 'id',
                'studentNo' => 'student_no',
                'name' => 'name',
                'sex' => 'sex',
                'classId' => 'class_id',
                'address' => 'address',
                'phone' => 'phone',
                'created' => 'created',
                'updated' => 'updated',
                'attributeData' => 'attributes',
            ));
    }
    public static function attributesList()
    {
        return [
            'id',
            'studentNo',
            'name',
            'sex',
            'classId',
            'address',
            'phone',
        ];
    }

    /**
     * @return User
     */
    public function user() {
        return array_values(User::find(new Query('internalId', $this->id)))[0];
    }

    /**
     * @return StudentClass
     */
    public function studentClass() {
        return StudentClass::load($this->classId);
    }

    public function remove() {
        $courseSelections = CourseSelection::find(new Query('studentId', $this->id), ['nolimit' => 1]);
        foreach ($courseSelections as $courseSelection) $courseSelection->remove();
        $users = User::find(new Query('internalId', $this->id), ['nolimit' => 1]);
        foreach ($users as $user) $user->delete();
        $this->delete();
    }

    public function totalCredits($pass = true) {
        $q = new AndQuery();
        $q->add(new Query('studentId', $this->id));
        $q->add($pass ? new RangeQuery('result', 60, null) : new RangeQuery('result', null, 59));
        $courseSelections = CourseSelection::find($q, ['nolimit' => 1]);
        $sum = 0;
        /**
         * @var CourseSelection $courseSelection
         */
        foreach ($courseSelections as $courseSelection) $sum += $courseSelection->courseClass()->course()->credit;
        return $sum;
    }
}